package simbot.example.demo.serializer;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * Created by henery on 2017/6/13.
 */
@Component
public class JsonDateSerializer extends JsonSerializer<Long> {

    @Override
    public void serialize(Long time, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException, JsonProcessingException {
        if (time == 0) {
            jsonGenerator.writeString("");
        } else {
            String formattedDate = "";
            Date date = new Date(time);

            SimpleDateFormat todayFormat = new SimpleDateFormat("HH:mm");
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

            if(isToday(date)) {
                formattedDate = dateFormat.format(date);
            } else {
                formattedDate = dateFormat.format(date);
            }


            jsonGenerator.writeString(formattedDate);
        }

    }

    private boolean isToday(Date date) {
        Date now = new Date();

        Calendar todayCalendar = Calendar.getInstance();
        todayCalendar.setTime(now);
        int todayYear = todayCalendar.get(Calendar.YEAR);
        int todayMonth = todayCalendar.get(Calendar.MONTH);
        int todayDay = todayCalendar.get(Calendar.DAY_OF_MONTH);

        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH);
        int day = calendar.get(Calendar.DAY_OF_MONTH);

        if(todayYear == year && todayMonth == month && todayDay == day) {
            return true;
        } else {
            return false;
        }
    }
}
